package com.hz.pro.kitchen.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {
    private static final char[] hexDigits = new char[]{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    private static final String DEFAULT_CHARSET = "UTF-8";

    private static final String DEFAULT_ALGORITHM = "MD5";


    public static String getMD5String(String str) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return bufferToHex(getMD5Byte(str));
    }

    public static byte[] getMD5Byte(String str) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        byte[] buffer = str.getBytes(DEFAULT_CHARSET);
        MessageDigest messagedigest = MessageDigest.getInstance(DEFAULT_ALGORITHM);
        return messagedigest.digest(buffer);
    }


    private static String bufferToHex(byte[] bytes) {
        return bufferToHex(bytes, 0, bytes.length);
    }

    private static byte[] hex2Bytes(String src) {
        int i = src.length() / 4;
        byte[] data = new byte[i];

        for(int j = 0; j < i; ++j) {
            String str = src.substring(j * 4 + 2, (j + 1) * 4);
            data[j] = (byte)Integer.parseInt(str, 16);
        }

        return data;
    }

    private static String bufferToHex(byte[] bytes, int m, int n) {
        StringBuffer stringbuffer = new StringBuffer(2 * n);
        int k = m + n;

        for(int l = m; l < k; ++l) {
            appendHexPair(bytes[l], stringbuffer);
        }

        return stringbuffer.toString();
    }

    private static void appendHexPair(byte bt, StringBuffer stringbuffer) {
        char c0 = hexDigits[(bt & 240) >> 4];
        char c1 = hexDigits[bt & 15];
        stringbuffer.append(c0);
        stringbuffer.append(c1);
    }

    public static void main(String[] args) throws Exception{
        System.out.println(getMD5String("123456"));
    }
}
